# Author: Yunqiao Zhang
# Email: zhangyunqiao@gmail.com

from django.db import models
from django.contrib.auth.models import User

class CommentBoard(models.Model):
  '''
  This class simply represents a group of Comments.
  '''
  creat_date = models.DateTimeField(auto_now_add = True)
  description = models.CharField(max_length = 256, blank = True)

  def __unicode__(self):
    return self.description

  @staticmethod
  def create_board(description = ''):
    '''
    This function will create a new CommentBoard in database
    and return this CommentBoard.
    '''
    return CommentBoard.objects.create(description = description)

  @staticmethod
  def get_board(id):
    '''
    Get board by id.
    '''
    # If CommentBoard does not exist, return None.
    try:
      return CommentBoard.objects.get(id = id)
    except:
      return None

  def add_comment(self, content, user=None):
    '''
    Add one comment to comment board and return this comment.
    '''
    return Comment.objects.create(
        content=content,
        author = user,
        comment_board = self)

  def get_comments(self, n=None):
    '''
    Return all comments in this CommentBoard as a list.
    '''
    if n is None:
      return list(self.comment_set.order_by('-comment_date').all())
    else:
      return list(self.comment_set.order_by('-comment_date')[:n])




class Comment(models.Model):
  '''
  This class represents a single comment by a user. It
  can be grouped by CommentBoard.
  '''
  content = models.CharField(max_length = 1024)
  comment_date = models.DateTimeField(auto_now_add = True)
  author = models.ForeignKey(User, null = True)
  comment_board = models.ForeignKey(CommentBoard)

  def __unicode__(self):
    return self.content

